package twt.practice.votingsystem.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import twt.practice.votingsystem.dao.ManageMapper;
import twt.practice.votingsystem.service.ManageService;
import twt.practice.votingsystem.utils.APIResponse;

import java.util.concurrent.locks.ReentrantLock;

@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    ManageMapper manageMapper;

    private static ReentrantLock lock = new ReentrantLock();

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse addVote(String title_context){
        lock.lock();
        try {
            return APIResponse.success(manageMapper.addVote(title_context));
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500, "添加失败");
        }finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse addChoice(Integer title_id, String choice_context){
        lock.lock();
        try {
            return APIResponse.success(manageMapper.addChoice(title_id, choice_context));
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500, "添加失败");
        }finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse deleteVote(String title_context){
        lock.lock();
        try {
            return APIResponse.success(manageMapper.deleteVote(title_context));
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500, "删除失败");
        }finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse deleteChoice(String title_context, String choice_context){
        lock.lock();
        try {
            return APIResponse.success(manageMapper.deleteChoice(title_context, choice_context));
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500, "删除失败");
        }finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse getConsequence(){
        lock.lock();
        try{
            return APIResponse.success(manageMapper.getConsequence());
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500, "查询失败");
        }finally {
            lock.unlock();
        }
    }
}
